package nju.software.xkxt.data.dao.implement;

import java.util.List;

import nju.software.xkxt.data.dao.ScoreDao;
import nju.software.xkxt.data.dataobject.ScoreDO;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class ScoreDaoImpl extends HibernateDaoSupport implements ScoreDao {

	@Override
	public boolean updateScore(List<ScoreDO> scoreDOs) {
		boolean isSuccess = false;
		for (ScoreDO scoreDO : scoreDOs) {
			if (scoreDO != null) {
				this.getHibernateTemplate().update(scoreDO);
				isSuccess = true;
			} else {
				return isSuccess;
			}
		}

		return isSuccess;
	}

	@Override
	public int getMaxSid() {
		String hql = "select max(SId) from ScoreDO";
		Session session = this.getSession();
		Query query = session.createQuery(hql);
		int maxId;
		if (query.uniqueResult() != null) {
			maxId = (Integer) query.uniqueResult();
		} else {
			maxId = 0;
		}
		return maxId;
	}

	@Override
	public int addScore(ScoreDO scoreDO) {
		int state;// 0代表失败，1代表成功，2代表已经存在该数据
		String sql = "select count(*) from ScoreDO where CId=:cid and UId=:uid and TId=:tid";
		Session session = this.getSession();
		Query query = session.createQuery(sql);
		query.setParameter("cid", scoreDO.getCId());
		query.setParameter("uid", scoreDO.getUId());
		query.setParameter("tid", scoreDO.getTId());
		long num = (Long) query.uniqueResult();
		if (num == 0) {
			if (scoreDO != null) {
				getHibernateTemplate().save(scoreDO);
				state = 1;
			} else
				state=0;
		} else {
			state = 2;
		}
		return state;
	}

	@Override
	public List<ScoreDO> getsScoreDOsByCidAndTid(int cid, int tid) {
		String hql = "from ScoreDO where CId =" + cid + "and TId = " + tid;
		List<ScoreDO> scoreDOs = getHibernateTemplate().find(hql);
		return scoreDOs;
	}

	@Override
	public ScoreDO getScoreByUidAndCid(int uid, int cid) {
		String hql = "from ScoreDO where UId=" + uid + "and CId=" + cid;
		List<ScoreDO> scoreDO = getHibernateTemplate().find(hql);
		return scoreDO != null ? scoreDO.get(0) : null;
	}

}
